package com.example.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @className: UserController
 * @author: Joe
 * @create: 2023-02-06 16:27
 * @description:
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 获取gitee第三方登录信息
     * @param code
     * @return
     */
    @GetMapping("/callback")
    public Object callback(String code) {
        //创建一个map来封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","fc197c65bcbac968f750dbd1d04cadac6a76ec2451e17c308b118afdcbc1cedf");
        map.put("client_secret","4008f3d802723a971cac19f60a273cf56960b1f8b2d09267afa41f36515a13af");
        map.put("redirect_uri","http://localhost:8080/git");
        //发送post请求,获取token
        String info = HttpUtil.post("https://gitee.com/oauth/token", map);
        //转换成json对象
        JSONObject jsonObject = JSONUtil.parseObj(info);
        String accessToken = (String)jsonObject.get("access_token");
        String str = HttpUtil.get("https://gitee.com/api/v5/user?access_token=" + accessToken);
        JSONObject jsonObject1 = JSONUtil.parseObj(str,true);
        //用户信息存入redis，设置过期策略
        redisTemplate.opsForValue().set("user",jsonObject1,24, TimeUnit.HOURS);
        return jsonObject1;
    }
}
